package com.xckj.cycling.utils

import android.content.Context
import android.content.res.Resources
import android.os.LocaleList
import android.text.TextUtils
import com.xckj.cycling.context.AppContext
import com.xckj.cycling.global.Constant
import java.util.*

/**
 * APP 语言工具
 */
object LanguageUtils {

    private var currentLanguage: String = ""

    init {
        val s = SpUtil.getString(AppContext.globalContext(), Constant.LANGUAGE)
        currentLanguage = if (TextUtils.isEmpty(s)) "" else s
    }

    fun setCurrentLanguage(lan: String?) {
        currentLanguage = lan ?: ""
        SpUtil.put(AppContext.globalContext(), Constant.LANGUAGE, currentLanguage)
        AppContext.globalContext().resources.updateConfiguration(AppContext.globalContext().resources.configuration.apply {
            setLocales(getLocal() ?: Resources.getSystem().configuration.locales)
        }, AppContext.globalContext().resources.displayMetrics)
    }

    @JvmStatic
    fun getLanguage(): String {
        if (TextUtils.isEmpty(currentLanguage)) {
            val app = AppContext.globalContext()
            val str = app.resources.configuration.locales.get(0)
            return str.language
        }
        return currentLanguage
    }

    fun newContext(context: Context): Context {
        val r = context.resources
        val c = r.configuration
        getLocal()?.apply {
            c.setLocales(this)
            return context.createConfigurationContext(c)
        }
        return context
    }

    fun getLocal(): LocaleList? {
        return when (currentLanguage) {
            "zh" -> {
                LocaleList(Locale.CHINA)
            }

            "en" -> {
                LocaleList(Locale.US)
            }

            "es" -> {
                LocaleList(Locale("es"))
            }

            else -> {
                null
            }
        }
    }
}